-- Leviathan (c) v.v.balashoff
local Class = require('leviathan/Class')

local InputSystem = Class:derive('UIInputSystem')

function InputSystem:new(domain)
    self.name = 'InputSystem'
    self.domain = domain
end

function InputSystem:update(dt)
    local buttonEntity = nil -- entity with button pressed component
    local mouse = nil

    local inputDomain = world:getDomain('Input')

    -- check is there any click
    local ent = inputDomain.entities
    for i = 1, #ent do
        if ent[i]:getComponent('ButtonAsyncPressedComponent') then
            buttonEntity = ent[i]
        end
    end

    -- look entities in reverse order
    if buttonEntity then
        local buttonName = buttonEntity.name
        local ent = self.domain.entities
        for i = #ent, 1, -1 do
            if ent[i].enabled then
                -- is clickable?
                local cc = ent[i]:getComponent('MouseClickComponent')
                if cc then
                    -- is hoverable?
                    local hc = ent[i]:getComponent('MouseHoverComponent')
                    if hc then
                        -- is hovered?
                        if hc.hovered then
                            -- is the right button pressed?
                            if not cc.button or (buttonName == cc.button) then
                                -- removing button pressed component
                                local comp = buttonEntity:getComponent('ButtonAsyncPressedComponent')
                                buttonEntity:deleteComponent(comp)
                                -- call button pressed function
                                local domain = cc.entity.domain
                                if cc.func then
                                    cc.func(domain, button)
                                end
                            end
                        end
                    end
                end
            end
        end
    end
end

return InputSystem
